package _21_多线程juc.demo01;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.function.BiConsumer;

@Data
@AllArgsConstructor
public class MyThread2_1 implements Runnable {
    private String url;
    private String fileName;

    @Override
    public void run() {
        try {
            // 下载图片，并打印当前线程名字
            FileUtils.copyURLToFile(new URL(url), new File(fileName));
            System.out.println(fileName + ": Thread.currentThread().getName() = " + Thread.currentThread().getName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        MyThread2_1 thread1 = new MyThread2_1(MyTestPictures.urlOfPic_1, MyTestPictures.fileNameOfPic_1);
        MyThread2_1 thread2 = new MyThread2_1(MyTestPictures.urlOfPic_2, MyTestPictures.fileNameOfPic_2);
        // new 一次 Thread 就是一个线程
        new Thread(thread1).start();
        new Thread(thread1).start();
        new Thread(thread2).start();

        new Thread(new MyThread2_1(MyTestPictures.urlOfPic_3, MyTestPictures.fileNameOfPic_3)).start();
        new Thread(new MyThread2_1(MyTestPictures.urlOfPic_4, MyTestPictures.fileNameOfPic_4)).start();

        // 获取图片资源的 key,value；对每张图片，new 一个线程下载
        Map<String, String> sourceMap = MyTestPictures.getPictureSource();
        sourceMap.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(String key, String value) {
                new Thread(new MyThread2_1(key, value)).start();
            }
        });
    }
}
